import dayJs from 'dayjs';
import {useUser} from '@/pinia-store/user.js';

/**
 * @function 获取uuid
 * @return {string} 返回uuid
 **/
export const getUuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * @function 扁平化tree
 * @param {array} tree 数据源
 * **/
export const dlatteningTree = (tree) => {
  let arr = []
  function fn(list) {
    list.forEach(item => {
      arr.push(item)
      if (item.children && item.children.length) {
        fn(item.children)
      }
    })
  }
  fn(tree)
  return arr
}

/**
 * @function 根据提供的value返回当前tree树结构
 * @param {array} tree 数据源
 * @param {string} value 匹配值
 * @param {object} load 配置项
 * @param {string} load.idKey 根据某个字段来匹配 默认id
 * @param {string} load.pidKey pidKey 默认pid
 * @return {array} 返回扁平后的当前tree数据
 * **/
export const findTree = (tree, value, load = {}) => {
  const arr = dlatteningTree(tree)
  load.idKey = load ? (load.idKey || 'id') : 'id'
  load.pidKey =  load ? (load.pidKey || 'pid') : 'pid'
  let currentTree = []
  function getCurrentTreeFn(list, value) {
    const current = list.find(item => {
      return item[load.idKey] === value
    })
    if (current) {
      if (current[load.pidKey]==='0') {
        currentTree.push(current)
      } else {
        currentTree.push(current)
        getCurrentTreeFn(list, current.pid)
      }
    }
  }
  getCurrentTreeFn(arr, value)
  return currentTree.reverse()
}

/**
 * @function 获取当前的时间段-中文
 * **/
export const timeSlotChinese = () => {
  let currentTime = new Date().getHours();
  let timeCustom = ''
  if (currentTime >= 5 && currentTime < 11) {
    timeCustom = '早上好'
  } else if (currentTime >= 11 && currentTime < 13) {
    timeCustom = '中午好'
  } else if (currentTime >= 13 && currentTime < 18) {
    timeCustom = '下午好'
  } else if (currentTime >= 18 || currentTime < 5) {
    timeCustom = '晚上好'
  }
  return timeCustom
}

/**
 * @function 获取字典名称
 * @param {String} dictType 字典类型
 * @param {String} dictValue 字典值
 * **/
export const getDictLabel = (dictType, dictValue) => {
  const { dictList } = useUser()
  const type = dictList.find((element) => element.dictType === dictType);
  if (type) {
    const val = type.dataList.find((element) => element.dictValue === dictValue + "");
    if (val) {
      return val.dictLabel;
    } else {
      return dictValue;
    }
  } else {
    return dictValue;
  }
}

/**
 * @function 获取字典列表
 * @param {String} dictType 字典类型
 * @param {String} dictValue 字典值
 * **/
export const getDictList = (dictType) => {
  const { dictList } = useUser()
  const type = dictList.find((element) => element.dictType === dictType);
  if (type) {
    return type.dataList
  } else {
    return [];
  }
}

/**
 * @function 权限检测（用于权限检测+其它条件判断）
 * @param {String} auth
 * **/
export const authSign = (auth) => {
  let flag = useUser().authSignList.findIndex(item=>item === auth)
  return flag === -1 ? false : true
}

/**
 * @function base64转file文件
 * @param {String} dataurl base64路径
 * @param {String} name fileName
 * **/
export const dataURLtoBlob = (dataurl, name) => {//base64转file
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], name, {
    type: mime,
  })
}

/**
 * @function 计算两个日期之间的天数
 * @param {String} date1 日期1
 * @param {String} date2 日期2 默认当天
 * **/
export const differenceDay = (date1, date2=new Date()) => {
  if (!date1) {
    return 0
  }
  let loadDate = dayJs(date1).set('h', 23).set('m', 59).set('s', 59)
  let currentDate = dayJs(date2)
  return loadDate.diff(currentDate, 'h') >= 0 ? loadDate.diff(currentDate, 'd') : -1
}

/**
 * @function 18位数雪花算法
 * **/
export const snowflakeAlgorithm = () =>{
  let snowflake = "";
  const timestamp = new Date().getTime().toString();
  
  snowflake += timestamp.slice(-10); // 使用时间戳的后10位作为一部分
  
  const remainingLength = 18 - snowflake.length;
  for (let i = 0; i < remainingLength; i++) {
    snowflake += Math.floor(Math.random() * 10); // 生成0到9的随机数字
  }
  
  return snowflake;
}

/**
 * @function 地区code转换地区文字
 * **/
export const areaCodeToText = (districtCode) => {
  const { areaTree } = useUser() // 项目有需要手动添加
  let text = ''
  function getAreaText(list) {
    list.forEach(item => {
      if (item.districtCode === districtCode) {
        text = item.areaName
        return
      } 
      if (item.children && item.children.length) {
        getAreaText(item.children)
      }
    })
  }
  getAreaText(areaTree)
  return text
}

/**
 * @function 文件链接转换文件名称
 * **/
export const fileLinkToName = (fileUrl) => {
  if (!fileUrl) {
    return
  }
  let firstIndex = fileUrl.lastIndexOf('/')
  let lastIndex = fileUrl.lastIndexOf('_')
  let fileType = fileUrl.slice(fileUrl.lastIndexOf('.'))
  return fileUrl.slice(firstIndex+1, lastIndex) + fileType
}